package controllers

import (
	"fuxi/echa"
	"fuxi/models"
	"fuxi/pkg"
	beego "github.com/beego/beego/v2/server/web"
	"time"
)

type UserController struct {
	beego.Controller
}
type Msg struct {
	Code int
	Msg  string
	Data interface{}
}

func (c *UserController) Login() {
	username := c.GetString("username")
	password := c.GetString("password")
	var ss models.User
	ss.Username = username
	ss.Password = pkg.Md5(password)
	if username == "" || password == "" {
		res := Msg{
			Code: 0,
			Msg:  "账号密码不能为空",
		}
		c.Data["json"] = res
		c.ServeJSON()
	}
	key := "password_count_err" + username
	count, _ := echa.Rdb.Get(echa.Ctx, key).Int()
	if count > 3 {
		echa.Rdb.Expire(echa.Ctx, key, time.Hour*2)
		res := Msg{
			Code: 0,
			Msg:  "密码错误三次封禁两小时",
		}
		c.Data["json"] = res
		c.ServeJSON()
	}
	if err := ss.Gets(); err != nil {
		res := Msg{
			Code: 0,
			Msg:  "系统错误",
		}
		c.Data["json"] = res
		c.ServeJSON()
	}
	if ss.ID == 0 {
		res := Msg{
			Code: 0,
			Msg:  "账号不存在，请重新输入",
			Data: nil,
		}
		c.Data["json"] = res
		c.ServeJSON()
	}
	if ss.Password != password {
		echa.Rdb.Incr(echa.Ctx, key)
		res := Msg{
			Code: 0,
			Msg:  "密码错误，重新输入",
		}
		c.Data["json"] = res
		c.ServeJSON()
	}
	res := Msg{
		Code: 200,
		Msg:  "登陆成功",
	}
	c.Data["json"] = res
	c.ServeJSON()
}
